package com.hao.tool.extra.poi.word;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 使用phantomjs浏览器截取图片
 *
 * @author: lanyh
 * @version: 1.0
 * @date: 2019/3/1 09:27
 * @description:
 */
public class DownloadImageUtil {
    private static final Logger log = LoggerFactory.getLogger(DownloadImageUtil.class);
    /**
     * phantomjs浏览器路径
     */
    private static final String PHANTOM_PATH = "D:/phantomjs-2.1.1-windows/bin/phantomjs";
    /**
     * 截图js的路径
     */
    private static final String TEST_JS = "E:/temp/operation/echarts_load.js ";

    /**
     * @param url         访问的页面URL
     * @param tNames      生成统计图的名称
     * @param projectPath 项目名称
     */
    public static void downloadImage(String url, String tNames, String projectPath) {

        String tName = tNames.replace("-", "");
        String cmdStr = projectPath + PHANTOM_PATH + "  " + projectPath + TEST_JS + "  " + url + "  " + tName;
        log.info("命令行字符串:{}", cmdStr);
        System.out.println(cmdStr);
        Runtime rt = Runtime.getRuntime();
        try {
            Process p = rt.exec(cmdStr);

            InputStream is = p.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
            StringBuilder stringBuilder = new StringBuilder();
            String tmp;
            while ((tmp = bufferedReader.readLine()) != null) {
                stringBuilder.append(tmp);
            }
            System.out.println(stringBuilder.toString());

        } catch (IOException e) {
            log.error("执行phantomjs的指令失败！请检查是否安装有PhantomJs的环境或配置path路径！PhantomJs详情参考这里:http://phantomjs.org", e);
        }
    }
}